package com.excesys.exsecs.handler;

import cn.hutool.json.JSONObject;
import com.excesys.exsecs.access.constant.RedisConstant;
import com.excesys.exsecs.access.service.ProtocolTransitionService;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 消费者线程
 *
 */
@Slf4j
public class MessageConsumer implements Runnable {

	private final ProtocolTransitionService protocolTransitionService;

	private JSONObject payloadJson;

	private AtomicInteger counter;

	public MessageConsumer(JSONObject payloadJson, AtomicInteger counter,
                           ProtocolTransitionService protocolTransitionService) {
		this.payloadJson = payloadJson;
		this.counter = counter;
		this.protocolTransitionService = protocolTransitionService;
	}

	@Override
	public void run() {
		counter.incrementAndGet();
		Date dateDebug = new Date();
		try {
			if (payloadJson.getInt(RedisConstant.ONLINE) == 1){
				protocolTransitionService.ayncDeal(payloadJson);
			} else {
				//设备离线处理
				protocolTransitionService.offlineDeal(payloadJson);
			}
		}
		catch (Exception e) {
			log.error(e.toString());
		}
		finally {
			// log.info("消费消息···{}",counter);
			counter.decrementAndGet();
			Date dateEnd = new Date();
			long l = dateEnd.getTime() - dateDebug.getTime();
			// log.info("执行耗时：{}",l);
		}
	}

}
